from rest_framework.views import exception_handler
from rest_framework.response import Response
from rest_framework import status
import logging

logger = logging.getLogger(__name__)


def custom_exception_handler(exc, context):
    """自定义异常处理器"""
    # 调用DRF默认的异常处理器
    response = exception_handler(exc, context)
    
    if response is not None:
        # 记录异常日志
        logger.error(f"API异常: {exc}", exc_info=True)
        
        # 统一异常响应格式
        custom_response_data = {
            'success': False,
            'message': '请求处理失败',
            'errors': None,
            'code': response.status_code
        }
        
        # 根据不同的异常类型设置不同的消息
        if response.status_code == 400:
            custom_response_data['message'] = '请求参数错误'
            custom_response_data['errors'] = response.data
        elif response.status_code == 401:
            custom_response_data['message'] = '未授权访问'
        elif response.status_code == 403:
            custom_response_data['message'] = '权限不足'
        elif response.status_code == 404:
            custom_response_data['message'] = '资源不存在'
        elif response.status_code == 405:
            custom_response_data['message'] = '请求方法不允许'
        elif response.status_code == 429:
            custom_response_data['message'] = '请求过于频繁'
        elif response.status_code >= 500:
            custom_response_data['message'] = '服务器内部错误'
        
        response.data = custom_response_data
    
    return response


class BusinessException(Exception):
    """业务异常"""
    def __init__(self, message, code=400):
        self.message = message
        self.code = code
        super().__init__(message)


class ValidationException(BusinessException):
    """验证异常"""
    def __init__(self, message, errors=None):
        super().__init__(message, 400)
        self.errors = errors


class PermissionException(BusinessException):
    """权限异常"""
    def __init__(self, message="权限不足"):
        super().__init__(message, 403)


class ResourceNotFoundException(BusinessException):
    """资源不存在异常"""
    def __init__(self, message="资源不存在"):
        super().__init__(message, 404)
